
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <limits.h>
#include <string.h>
#include <unistd.h>

#ifndef PATH_MAX
#define PATH_MAX 1024
#endif

static void *handle = NULL;

ssize_t (*real_recv)(int socket, void *buffer, size_t length, int flags);

size_t get_executable_path( char* processdir,char* processname, size_t len)
{
	char* path_end;
	if(readlink("/proc/self/exe", processdir,len) <=0)
		return -1;
	path_end = strrchr(processdir, '/');
	if(path_end == NULL)
		return -1;
	++path_end;
	strcpy(processname, path_end);
	*path_end = '\0';
	return (size_t)(path_end - processdir);
}


ssize_t recv(int socket, void *buffer, size_t length, int flags)
{
	char *error;
	ssize_t ret = 0;
	if (handle == NULL) {
#ifndef ELF32
		handle = dlopen("/lib64/libc.so.6", RTLD_LAZY);
#else
		handle = dlopen("/lib/libc.so.6", RTLD_LAZY);
#endif
		if ((error = dlerror()) != NULL){
			puts(error);
			exit(-1);
		}
	}

	if (handle == NULL) {
		puts("dl not open libc.so\n");
		exit(-1);
	}

	if (real_recv == NULL) {
		real_recv = dlsym(handle, "recv");
		if ((error = dlerror()) != NULL){
			puts(error);
			exit(-1);
		}
	}
	ret = real_recv(socket, buffer, length, flags);

	char path[PATH_MAX];
	char processname[1024];
	get_executable_path(path, processname, sizeof(path));
	if (strcmp(processname, "armasm") == 0) {
		puts("<<<<<<<");
		printf("recv data: %s\n", buffer);
	}
	return ret;
}


ssize_t (*real_send)(int socket, const void *buffer, size_t length, int flags);

ssize_t send(int socket, const void *buffer, size_t length, int flags)
{
	char *error;
	ssize_t ret = 0;
	if (handle == NULL) {
#ifndef ELF32
		handle = dlopen("/lib64/libc.so.6", RTLD_LAZY);
#else
		handle = dlopen("/lib/libc.so.6", RTLD_LAZY);
#endif
		if ((error = dlerror()) != NULL){
			puts(error);
			exit(-1);
		}
	}

	if (handle == NULL) {
		puts("dl not open libc.so\n");
		exit(-1);
	}

	if (real_send == NULL) {
		real_send = dlsym(handle, "send");
		if ((error = dlerror()) != NULL){
			puts(error);
			exit(-1);
		}
	}
	char path[PATH_MAX];
	char processname[1024];
	get_executable_path(path, processname, sizeof(path));
	if (strcmp(processname, "armasm") == 0) {
		puts(">>>>>>>>");
		printf("send data: %s\n", buffer);
	}
	
	ret = real_send(socket, buffer, length, flags);
	return ret;
}